package com.idol.controller;

import com.idol.service.ITockenService;
import com.idol.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author SupremeSir
 * @description 用户相关 API
 * @className UserController
 * @date 2021/2/15 22:13
 **/
@RequestMapping("user")
@RestController
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ITockenService tockenService;

    /**
     * 注册用户并设置 Cookie
     * @param email 用户邮箱
     * @param password  用户密码
     * @param code 验证码
     * @param response HttpServletResponse用以设置 Cookie
     */
    @RequestMapping("register/{email}/{password}/{code}")
    public boolean regist (@PathVariable("email") String email, @PathVariable("password") String password,
                           @PathVariable("code") String code, HttpServletResponse response) {
        boolean regist = userService.regist(email, password, code);
        if (regist) {
            String uuid = UUID.randomUUID().toString();
            Cookie cookie = new Cookie("token", uuid);
            cookie.setPath("/");
            cookie.setMaxAge(5 * 60);
            response.addCookie(cookie);
            tockenService.saveTocken(email, uuid);
        }
        return regist;
    }

    /**
     * 用户登录并设置 Cookie
     * @param email 用户邮箱
     * @param password 用户密码
     * @param response HttpServletResponse用以设置 Cookie
     */
    @RequestMapping("login/{email}/{password}")
    public boolean login(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse response) {
        String dbEmail = userService.login(email, password);
        if (StringUtils.isBlank(dbEmail)) {
            return false;
        }
        String uuid = UUID.randomUUID().toString();
        Cookie cookie = new Cookie("token", uuid);
        cookie.setPath("/");
        cookie.setMaxAge(5 * 60);
        response.addCookie(cookie);
        return tockenService.saveTocken(email, uuid);
    }

    /**
     * 根据 Token 获取用户信息
     * @param request HttpServletRequest 用以获取 Cookie
     * @return
     */
    @RequestMapping("info")
    public String getUserInfoByToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String token = null;
        for (Cookie cookie : cookies) {
            if ("token".equals(cookie.getName())){
                token = cookie.getValue();
            }
        }
        if (null == token) {
            return null;
        }
        String email = tockenService.getInfo(token);
        return email;
    }
}
